<?php
namespace App\Wen\Utils;

use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxCircleRepositores;
use App\Http\Controllers\Api\Repositories\WxCommentRepositores;
use App\Jobs\Posts\UpdatePostFieldsJob;
use App\Jobs\Posts\UpdatePostFilesIdJob;
use App\Jobs\Posts\UpdatePostGoodsIdJob;
use App\Jobs\Posts\UpdatePostSoundsIdJob;
use App\Jobs\Posts\UpdatePostTagIdJob;
use App\Jobs\Posts\UpdatePostTenantObjJob;
use App\Jobs\Posts\UpdatePostVideoIdJob;
use App\Jobs\Posts\UpdatePostVoteIdJob;
use App\Jobs\System\CheckBatchCahceDataLossJob;
use App\Jobs\UpdatePostImgCountJob;
use App\Jobs\UpdatePostImgWHJob;
use App\Jobs\VideoSnapshotJob;
use App\Models\Bureau\WxBureau;
use App\Models\Posts\WxComment;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPost as Model;
use App\Models\Posts\WxPostsAddress;
use App\Models\Posts\WxPostsFile;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsSound;
use App\Models\Posts\WxPostsVideo;
use App\Models\Posts\WxPostsVote;
use App\Models\Circle\WxCircle;
use App\Models\Posts\WxPostsPayContent;
use App\Models\Posts\WxTag;
use App\Models\Shop\WxShopGoods;
use App\Models\Used\WxUsedGood;
use App\Models\User\WxUserPay;
use App\Models\User\WxUserVisit;
use App\Models\User\WxUserVote;
use App\Models\Voter\WxVoter;
use App\Models\Posts\WxPostsField;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class PostUtils{

    public static $top_posts_id = null;
    public static $ad_config = null;
    public static $app_emoji_alt_str = null;
    public static $APP_IS_MULTI_SITE = null;
    public static $show_multi_site_scenes = [5,6,8,7,10];
    public static $force_show_multi_site = null;
    public static $media_style = 2;

    public static function reset_loop(){
        self::$media_style = Settings::get('sticky_list_media_style', 2, true);
        is_mini_examine_mode(11);
    }


    public static function mediaStyle(&$v, $scene){
        global $__MINI_GLOBAL_MODE__;
        if(self::$media_style == 2 || $scene == 9){
            if($v->video){
                $v->media_style = 3;
            }else if($v->is_blur != 0){
                $v->media_style = 1;
            }else if($v->post_type == 'single'){
                $v->media_style = 1;
            }else if($v->refer_id > 0){
                $v->media_style = 1;
            }else if($v->wechat_sph){
                $v->media_style = 1;
            }else if($v->images->count() > 0){
                if($scene == 9){
                    $v->media_style = 0;
                }else{
                    if($v->is_all_img_meet == 1){
                        $v->media_style = 2;
                    }else{
                        $v->media_style = 1;
                    }
                }
            }
        }else{
            $v->media_style = 1;
        }

        if($v->video){
            $v->media_style_sticky = 3;
        }else if($v->is_blur != 0){
            $v->media_style_sticky = 1;
        }else if($v->post_type == 'single'){
            $v->media_style_sticky = 1;
        }else if($v->refer_id > 0){
            $v->media_style_sticky = 1;
        }else if($v->wechat_sph){
            $v->media_style_sticky = 1;
        }else if($v->img_count > 0){
            $v->media_style_sticky = 0;
        }

        if($__MINI_GLOBAL_MODE__ == 'examine'){
            $v->cfs = 1;
        }else if($v->user['setting']['privacy_get_my_wechat'] == 5 || $v->user['setting']['privacy_get_my_phone'] == 5){
            if($v->user['setting']['privacy_get_my_wechat'] == 5 && $v->user['setting']['privacy_get_my_phone'] == 5){
                $v->cfs = 2;
            }else{
                if($v->user['setting']['privacy_get_my_wechat'] == 5){
                    $v->cfs = 3;
                }else{
                    $v->cfs = 4;
                }
            }
        }else{
            $v->cfs = 1;
        }
    }


    public static function relatProcess(&$v, &$relat_cover){
        if(!_empty_($v->useds)){
            $v->used_goods = WxUsedGood::whereIn('id', $v->useds)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $v->useds) . '"' . ")"))->get();
            if($v->used_goods){
                $v->used_goods->map(function ($v) use (&$relat_cover){
                    ShopUtils::used_process($v);
                    if(_empty_($relat_cover)){
                        $relat_cover = $v->pic;
                    }
                    return $v;
                });
            }
        }

        if(!_empty_($v->bureaus)){
            $v->bureau_list = WxBureau::whereIn('id', $v->bureaus)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $v->bureaus) . '"' . ")"))->get();
            if($v->bureau_list){
                $v->bureau_list->map(function ($v) use (&$relat_cover){
                    BureauUtils::bureau_process($v);
                    if(_empty_($relat_cover)){
                        $relat_cover = $v->pic;
                    }
                    return $v;
                });
            }
        }

        if($v->voter_id > 0){
            $v->voter = WxVoter::find($v->voter_id);
            if($v->voter['banners']){
                if(_empty_($relat_cover)){
                    $relat_cover = $v->voter['banners'][0];
                }
            }
        }

    }

    public static function mediaProcess(&$v, $uid, $scene, $list_style = 0, $is_refer = false){
        global $__MINI_GLOBAL_DEVICE__, $__MINI_GLOBAL_MODE__;
        $main_img = '';
        $squre_img = '';
        $img_count = 0;
        $swiperImgHeight = 0;
        $relat_cover = '';

        $refer_id = $v->refer_id;
        $v->user = UserUtils::get_cached_user($v->user_id);

        if($v->video_id === Null){
            $v->video = WxPostsVideo::where('posts_id', $v->id)->first();//视频
            UpdatePostVideoIdJob::dispatch($v->id);
        }else if($v->video_id > 0){
            $v->video = WxPostsVideo::where('id', $v->video_id)->first();//视频
        }else if($v === 0){
            $v->video = null;
        }

        self::relatProcess($v, $relat_cover);

        if($v->is_wechat_sph){
            $v->wechat_sph = get_post_meta($v->id, 'wechat_sph', 'j');
        }else{
            $v->wechat_sph = null;
        }
        //  注意这里不能直接截取，需要长度判断是否是有媒体文件
        $v->posts_content_origin = $v->posts_content;
        $v->posts_content_raw = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '',$v->posts_content);
        $old_post_type = $v->post_type;
        $v->post_type = self::post_type($v);

        if($v->post_type && $old_post_type != $v->post_type){
            Redis::sadd('post:type:to:update:set', json_encode(['id'=>$v->id, 'type'=>$v->post_type]));
        }
        $v->posts_content_raw =html_entity_decode( _mini_phone(_mini_aite_replace(_mini_emoji($v->posts_content_raw, true), true)) );
        if($v->post_type == 'words'){
            $v->posts_content = trim_all_space(strip_tags($v->posts_content, ['<mini-aite>','<a>', '<br>', '<p>', '<ul>', '<ol>', '<li>','<mini-emoji>', '<mini-text-img>', '<mini-contact>']), true, true);
        }else if($v->post_type == 'single'){
            if($__MINI_GLOBAL_MODE__ == 'examine'){
                $v->posts_content = preg_replace("/<(video|audio).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '', $v->posts_content);
            }
            $v->posts_content_raw = self::get_the_title(trim_all_space(strip_tags($v->posts_content_raw, ['<br>']), true, true), $v->id, 50);
            if($scene != 9){
                if(_empty_($v->posts_title)){
                    $v->posts_title = $v->posts_content_raw;
                }
            }
        }else if($v->post_type == 'video'){
            $v->posts_content_raw = trim_all_space($v->posts_content_raw, true, true);
            if($scene == 75){
                $v->posts_content_raw = self::get_the_title(strip_tags($v->posts_content_raw, ['<br>']), $v->id, 30);
            }
        }else{
            $v->posts_content_raw = trim_all_space($v->posts_content_raw, true);
        }



        // 图片处理开始
        $loop_is_nine_grid = false;
        if($is_refer || ($scene != 9 && self::$media_style == 1)){
            $loop_is_nine_grid = true;
        }


        if($v->post_type == 'single'){
            $images_arr = [];
            WxPostsImg::where('posts_id', $v->id)->get(['id','img_url', 'posts_id','width', 'height'])->map( function ($postImg) use (&$v){
                if($postImg->height > 0){
                    $v->posts_content .= '<img src="'.$postImg->img_url.'" style="height: '.$postImg->height.'px;width: '.$postImg->width.'px;" />';
                }else{
                    $v->posts_content .= '<img src="'.$postImg->img_url.'" />';
                }
            });
            $v->posts_content = preg_replace_callback("/<img.*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", function ($r) use (&$images_arr){
                $images_arr[] = $r[1];
                return '<img src="'.Utils::imgWithStyle($r[1], 0).'">';
            }, $v->posts_content);
            if($images_arr){
                $img_count += count($images_arr);
                $images = [];
                $i = 0;
                foreach ($images_arr as $url){
                    if(_empty_($main_img)){
                        if($scene == 90004){
                            $main_img = $url;
                            $squre_img = Utils::imgWithStyle($url, 2);
                        }else if( $scene == 90003 ){
                            $main_img = $url . '?imageMogr2/thumbnail/400x/crop/400x400/gravity/center/interlace/0/quality/100';
                            $squre_img = Utils::imgWithStyle($url, 2);
                        }else{
                            $main_img = Utils::imgWithStyle($url, 1);
                            $squre_img = Utils::imgWithStyle($url, 2);
                        }
                    }
                    if($i >= 3){
                        break;
                    }
                    $images[] = ['img_url'=>$url . '?imageMogr2/format/webp/interlace/0/crop/370x250/gravity/center/thumbnail/400x', 'posts_id' => $v->id];
                    $i ++;
                }
                if($__MINI_GLOBAL_DEVICE__ != 'pc'){
                    $v->images = $images;
                }
            }else{
                $v->images = [];
            }

        }else{
            $v->is_all_img_meet = 1;
            $v->images = WxPostsImg::where('posts_id', $v->id)->get(['id','img_url', 'posts_id','width', 'height'])->map( function ($postImg, $k) use (&$v, &$main_img, &$squre_img, $scene, &$swiperImgHeight, $refer_id,$is_refer, &$loop_is_nine_grid){
                if($postImg->width <= 0){
                    UpdatePostImgWHJob::dispatch($postImg->id);
                }
                if(_empty_($main_img)){
                    if($scene == 90004){
                        $main_img = $postImg->img_url;
                        $squre_img = Utils::imgWithStyle($postImg->img_url, 2);
                    }else if( $scene == 90003 ){
                        $main_img = $postImg->img_url . '?imageMogr2/thumbnail/400x/crop/400x400/gravity/center/interlace/0/quality/100';;
                        $squre_img = Utils::imgWithStyle($postImg->img_url, 2);
                    }else{
                        $main_img = Utils::imgWithStyle($postImg->img_url, 1);
                        $squre_img = Utils::imgWithStyle($postImg->img_url, 2);
                    }
                }
                $postImg->img_url = Utils::imgWithStyle($postImg->img_url, 0);
                if(self::$media_style == 2){
                    if($v->is_all_img_meet == 1){
                        if($postImg->height > 0 && $postImg->width / $postImg->height > 1.3 && $postImg->width >= 750){

                        }else{
                            $v->is_all_img_meet = 0;
                        }
                    }
                }
                if($scene != 9 && $v->is_all_img_meet == 0 && !$loop_is_nine_grid){
                    $loop_is_nine_grid = true;
                }
                if($loop_is_nine_grid){
                    if($k === 0){
                        $first_img_width = $postImg->width;
                        $first_img_height = $postImg->height;
                        if($first_img_width >= 640){
                            $old_widht = $first_img_width;
                            $first_img_width = 750;
                            $first_img_height = ceil( (750 * $first_img_height) / $old_widht );
                        }

                        // 根据高度缩小
                        if($first_img_height > 1000){
                            $old_height = $first_img_height;
                            $first_img_height = 1000;
                            $first_img_width =  ceil((1000 * $first_img_width) / $old_height);
                        }
                        $postImg->first_img_width = $first_img_width;
                        $postImg->first_img_height = $first_img_height;
                    }


                    self::postImgScale($postImg, false, $is_refer);
                }else{
                    self::postImgScale($postImg, true);
                    if($postImg->height > $swiperImgHeight){
                        $swiperImgHeight = $postImg->height;
                    }
                }
                return $postImg;
            });//图片
            if($v->images){
                $img_count += $v->images->count();
            }
            if($swiperImgHeight > 0){
                if($swiperImgHeight > 1000){
                    $v->swiperImgHeight = 1000;
                }else{
                    $v->swiperImgHeight = $swiperImgHeight;
                }
            }else{
                if($v->swiper_max_height){
                    $v->swiperImgHeight = $v->swiper_max_height;
                }else{
                    $v->swiperImgHeight = 400;
                }
            }
        }

        if($v->video && $v->video->video_thumb_url){
            if($scene == 90004){
                $main_img = $v->video->video_thumb_url;
                $squre_img = Utils::imgWithStyle($v->video->video_thumb_url, 2);
            }else if($scene == 90003){
                $main_img = $v->video->video_thumb_url . '?imageMogr2/thumbnail/400x/crop/400x400/gravity/center/interlace/0/quality/100';;
                $squre_img = Utils::imgWithStyle($v->video->video_thumb_url, 2);
            }else{
                $main_img = Utils::imgWithStyle($v->video->video_thumb_url, 1);
                $squre_img = Utils::imgWithStyle($v->video->video_thumb_url, 2);
            }
        }
        if($v->video){
            $img_count += 1;
        }


        if($main_img){
            $v->img = $main_img;
            $v->squre = $squre_img;
            $v->share_img = $main_img;
        }else if($v->wechat_sph && _array_key($v->wechat_sph, 'img', '')){
            $v->img = $v->wechat_sph['img'];
            $v->squre = $v->wechat_sph['img'];
            $v->share_img = $v->wechat_sph['img'];
        } else{
            if($relat_cover){
                $v->img = $relat_cover;
                $v->squre = Utils::imgWithStyle(Utils::imgWithStyle($relat_cover, 0, false, true), 2);
                $v->share_img = $relat_cover;
            }else{
                if($scene == 90003){
                    // 笔记分享
                    $v->img = Settings::get('img_share_default', '') . '?imageMogr2/thumbnail/400x/crop/400x400/gravity/center/interlace/0/quality/100';;
                }else if($scene == 90004){
                    $v->img = Settings::get('img_post_poster_default', '');
                }else{
                    $v->img = Utils::imgWithStyle(Settings::get('img_default', ''));
                }

                $v->share_img = Settings::get('img_share_default', '');
                $v->squre = Utils::imgWithStyle(Settings::get('img_default', ''), 2);
            }
        }

        if($v->img_count != $img_count || ($img_count > 0 && $v->swiperImgHeight != 400 && $v->swiperImgHeight != $v->swiper_max_height)){
            UpdatePostImgCountJob::dispatch($v->id, $img_count, $v->swiperImgHeight)->delay(now()->addSeconds(10));
            $v->img_count = $img_count;
        }

        if($img_count == 0){
            $v->random_bg = self::get_post_random_bg($v->id);
        }else{
            $v->random_bg = null;
        }

        if(!_empty_($refer_id)){

            if($v->img_count > 0 && $v->images && $v->images[0]['img_url']){
                $v->posts_content .= '<mini-text-img src="'.$v->images[0]['img_url'].'"></mini-text-img>';
                $v->images = [];
            }else{
                $v->images = [];
            }
            $v->is_only_text = 0;
        }

        if($loop_is_nine_grid){
            if($v->images && count($v->images) > 9){
                $v->images = ($v->images)->take(9);
            }
        }
    }

    public static function postImgScale(&$postImg, $is_swiper, $is_refer = false){
        if($is_swiper){
            // 根据宽度缩小
            if($postImg->width >= 640){
                $old_widht = $postImg->width;
                $postImg->width = 750;
                $postImg->height = (int)( (750 * $postImg->height) / $old_widht );
            }

            // 根据高度缩小
            if($postImg->height > 1000){
                $old_height = $postImg->height;
                $postImg->height = 1000;
                $postImg->width =  (int)((1000 * $postImg->width) / $old_height);
            }
        }else{
            // 九宫格场景
            if($is_refer){
                if($postImg->width > 0 && $postImg->width < 750){
                    if($postImg->height > 400){
                        $postImg->width /= 1.7;
                        $postImg->height /= 1.7;
                    }
                }
                if($postImg->width > 750 && $postImg->height > 500){
                    $postImg->width /= 2;
                    $postImg->height /= 2;
                }
                if($postImg->width >0 && $postImg->width < 150){
                    $old_widht = $postImg->width;
                    $postImg->width = 150;
                    $postImg->height = (int)( (150 * $postImg->height) / $old_widht );
                }

                if($postImg->height > 400){
                    $old_height = $postImg->height;
                    $postImg->height = 400;
                    $postImg->width =  (int)((400 * $postImg->width) / $old_height);
                }

            }else{
                if($postImg->width > 0 && $postImg->width < 750){
                    if($postImg->height > 400){
                        $postImg->width /= 1.7;
                        $postImg->height /= 1.7;
                    }
                }
                if($postImg->width > 750 && $postImg->height > 500){
                    $postImg->width /= 2;
                    $postImg->height /= 2;
                }
                if($postImg->width >0 && $postImg->width < 150){
                    $old_widht = $postImg->width;
                    $postImg->width = 150;
                    $postImg->height = (int)( (150 * $postImg->height) / $old_widht );
                }

                if($postImg->height > 700){
                    $old_height = $postImg->height;
                    $postImg->height = 700;
                    $postImg->width =  (int)((700 * $postImg->width) / $old_height);
                }
            }
        }
    }

    public static function defaultProcess($k, &$v, $scene = 0, $actree = null){
        global $__MINI_GLOBAL_CURRENT_USER_ID__;

        Redis::sadd('robot:timed:post:active', $v->id);
        self::circleProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene);

        global $__MINI_GLOBAL_PAYCODE_12__;
        if($v->has_fields === 1) {
            $v->fields = WxPostsField::find($v->id);
        }else if($v->has_fields === null){
            $v->fields = WxPostsField::find($v->id);
            UpdatePostFieldsJob::dispatch($v->id);
        }

        self::mediaProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene, 0);
        self::interact_process($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene);
        self::payContentProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene);

        if($actree){
            $ac_res = $actree->search($v->posts_content_raw);
            $pre_tags = '<span style="color: '.Settings::get('app_search_highlight_color').';">';
            $end_tag =   '</span>';
            if(self::$app_emoji_alt_str === null){
                self::$app_emoji_alt_str = Cache::get('app_emoji_alt_str', '');
            }
            $_tmp_posts_content_raw = $v->posts_content_raw;
            if($v->post_type == 'single'){
                if(mb_strlen($_tmp_posts_content_raw) > 55){
                    $_tmp_posts_content_raw = mb_substr($_tmp_posts_content_raw, 0, 55) . '...';
                }
            }else{
                if(mb_strlen($_tmp_posts_content_raw) > 100){
                    $_tmp_posts_content_raw = mb_substr($_tmp_posts_content_raw, 0, 100) . '...';
                }
            }
            foreach ($ac_res as $pos) {
                $searched_part = mb_substr($v->posts_content_raw,$pos[0],$pos[1] - $pos[0],'UTF-8');
                if(!self::$app_emoji_alt_str || !str_contains(self::$app_emoji_alt_str, $searched_part)){
                    $v->posts_content = str_replace($searched_part, $pre_tags.$searched_part.$end_tag, $v->posts_content);
                    $_tmp_posts_content_raw = str_replace($searched_part, $pre_tags.$searched_part.$end_tag, $_tmp_posts_content_raw);
                }
            }
            $v->posts_content_raw = $_tmp_posts_content_raw;
        }else{
            if($v->post_type == 'single'){
                if(mb_strlen($v->posts_content_raw) > 55){
                    $v->posts_content_raw = mb_substr($v->posts_content_raw, 0, 55) . '...';
                }
            }else{
                if(mb_strlen($v->posts_content_raw) > 100){
                    $v->posts_content_raw = mb_substr($v->posts_content_raw, 0, 100) . '...';
                }
            }

        }

        if($scene){
            if($scene == 1){
            }else if($scene == 6){
                if( get_circle_meta($v->circle_id, 'sticky', 'n') == $v->id ){
                    $v->is_sticky = true;
                }else{
                    $v->is_sticky = false;
                }
            }else if($scene == 8 || $scene == 5){
                if( get_user_meta($__MINI_GLOBAL_CURRENT_USER_ID__, 'sticky', 'n') == $v->id ){
                    $v->is_sticky = true;
                }else{
                    $v->is_sticky = false;
                }
            }else{
                $v->is_sticky = false;
            }
        }else{
            $v->is_sticky = false;
        }

        if($v->video && _empty_($v->video->video_thumb_url)){
            $v->video->video_thumb_url = Settings::get('img_video_default');
            VideoSnapshotJob::dispatch($v->video->id);
        }

        // 热帖榜
        if($__MINI_GLOBAL_PAYCODE_12__){
            if(self::$top_posts_id === null){
                if(Cache::has('realtime:posts:show_top:ids')){
                    self::$top_posts_id = json_decode(Cache::get('realtime:posts:show_top:ids', '[]'), true);
                }else{
                    self::$top_posts_id = false;
                }
            }
            if(self::$top_posts_id && isset(self::$top_posts_id[$v->id])){
                $v->post_top = self::$top_posts_id[$v->id];
            }else{
                $v->post_top = 0;
            }
        }else{
            $v->post_top = 0;
        }
        if(($k + 1) % 7 == 0){
            self::get_ad($v, $scene, false);
        }else if($scene == 9){
            self::get_ad($v, $scene, false);
        }else{
            $v->ad = null;
        }
        if($scene == 1){
            if( ($k + 3) % 5 == 0){
                $v->flow = self::get_flow();
            }
        }
        if(_empty_($v->flow)){
            $v->flow = null;
        }

        if($v->distance && $v->distance > 0){
            if($v->distance < 10){
                $v->distance = '<10m';
            }else if($v->distance >= 1000 && $v->distance <= 200000){
                $v->distance = '<'. round($v->distance / 1000, 2).'km';
            }else if($v->distance > 200000){
                $v->distance = round($v->distance / 1000, 2).'km';
            }else{
                $v->distance = '<'.(int)$v->distance.'m';
            }
        }else{
            $v->distance = '';
        }


        self::voteProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__);
        self::referProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene, 0);
        self::longtapProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene, 0);
        $v->post_show = true;


        self::tenant_obj_process($v, $scene);
        self::mediaStyle($v, $scene);
        self::presets($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene, false);
        $v->view_count = self::get_view_count($v->id);

        return $v;
    }

    public static function tenant_obj_process(&$v, $scene){
        if($v->tenant_obj === null){
            UpdatePostTenantObjJob::dispatch($v->id);
        }else{
            if(self::$force_show_multi_site === false){
                $v->tenant_obj = null;
            }
            if(self::$APP_IS_MULTI_SITE === null){
                self::$APP_IS_MULTI_SITE = env('APP_IS_MULTI_SITE', 0);
            }
            if(self::$APP_IS_MULTI_SITE > 0){
                if(self::$force_show_multi_site || in_array($scene, self::$show_multi_site_scenes)){
                    $v->tenant_obj = json_decode($v->tenant_obj, true);
                }else{
                    $v->tenant_obj = null;
                }
            }else{
                $v->tenant_obj = null;
            }
        }
    }

    public static function presets(&$v, $uid, $scene, $waterfall){
        if($scene != 9 && $v->posts_state === 0 && $v->is_examine == 1){
            $v->presets = _encodeURIComponent(json_encode([
                'raw'=> '',
                'user_name'=> $v->user ? $v->user['user_name'] : '',
                'user_avatar'=> $v->user ? $v->user['user_avatar'] : '',
                'imgHeight'=> $v->swiperImgHeight,
                'img'=> count($v->images) > 0 ? ($waterfall ? Utils::imgWithStyle($v->images[0]['img_url']) : $v->images[0]['img_url']) : '',
                'img_width' => count($v->images) > 0 ? ($v->images[0]['first_img_width'] ?? ($v->images[0]['width'] ?? 0) ) : 0,
                'img_height' => count($v->images) > 0 ? ($v->images[0]['first_img_height'] ?? ($v->images[0]['height'] ?? 0) ) : 0,
                'is_pay' => ($v->pay_obj && $v->pay_obj['is_payd'] === false && $v->pay_obj['has_img'] > 0) ? 1 : 0,
                'img_count' => $v->img_count,
                'comment_count' => $v->comment_count,
                'circle_name' => $v->circle ? $v->circle->circle_name : '',
                'head_portrait' => $v->circle ? $v->circle->head_portrait : '',
                'is_blur' => $v->is_blur,
                'cid' => _array_key($v->circle, 'id', 0),
                'civ' => _array_key($v->circle, 'can_i_visit', 0),
                'media_style' => $v->media_style_sticky,
                'cfs' => $v->cfs
            ]));
        }
    }

    /**
     * @param $v
     * @param $uid
     * @param $scene
     * @param int $style 0：列表式 1：瀑布流
     */
    public static function referProcess(&$v, $uid, $scene, $list_style = 0){
        if($v->refer_id && $v->refer_id > 0){
            $refer_post = WxPost::find($v->refer_id);
            if($refer_post){
                self::mediaProcess($refer_post, $uid, $scene, 0, true);
                self::circleProcess($refer_post, $uid, $scene);
                self::presets($refer_post, $uid, $scene, false);
                $v->refer = $refer_post;
            }else{
                $v->refer = null;
            }
        }else{
            $v->refer = null;
        }
    }

    /**
     * @param $v
     * @param $uid
     * @param $scene
     * @param int $style 0：列表式 1：瀑布流
     */
    public static function longtapProcess(&$v, $uid, $scene, $list_style = 0){
        $longtaps = [];
        $is_circle_master = ($v->circle && $uid && $v->circle['user_id'] == $uid);
        $is_user_special = is_object_user_special($uid, $v->tenant_id);
        $sticky_name = '全局置顶';
        if($scene == 1){
            $sticky_name = '全局置顶';
        }else if($scene == 6){
            $sticky_name = '内容置顶';
        }else if($scene == 5 || $scene == 8){
            $sticky_name = '主页置顶';
        }
        if($v->is_sticky){
            $sticky_name = '取消置顶';
        }
        if($uid != $v->user_id){
            if($scene == 80){
                // 不喜欢的笔记 页面
                $longtaps[] = [
                    'text' => '不感兴趣',
                    'emoji' => '💔',
                    'list' => [
                        [
                            'name' => '解除',
                            'action' => 'feedback-notlike-1',
                            'posts_id' => $v->id
                        ]
                    ]
                ];
            }else{
                $longtaps[] = [
                    'text' => '不感兴趣',
                    'emoji' => '💔',
                    'list' => [
                        [
                            'name' => '不喜欢该笔记',
                            'action' => 'feedback-notlike-1',
                            'posts_id' => $v->id
                        ],
                        [
                            'name' => '不喜欢该作者',
                            'action' => 'feedback-notlike-2',
                            'posts_id' => $v->id
                        ]
                    ]
                ];
            }
            if($scene != 80){
                $longtaps[] = [
                    'text' => '内容反馈',
                    'emoji' => '😣',
                    'list' => [
                        [
                            'name' => '广告',
                            'action' => 'report-0',
                            'posts_id' => $v->id,
                            'report_type' => 9,
                        ],
                        [
                            'name' => '不实信息',
                            'action' => 'report-0',
                            'posts_id' => $v->id,
                            'report_type' => 4,
                        ],
                        [
                            'name' => '色情政治',
                            'action' => 'report-0',
                            'posts_id' => $v->id,
                            'report_type' => 1,
                        ],
                        [
                            'name' => $is_user_special ? ($v->is_blur ? '取消不适' : '图片不适') : '图片不适',
                            'action' => $is_user_special ? 'blur' : 'report-0',
                            'posts_id' => $v->id,
                            'report_type' => 10,
                        ],
                    ]
                ];
            }
        }
        if($scene != 80){
            if($is_user_special || $uid == $v->user_id || $is_circle_master) {
                $lists = [];
                foreach (['sticky', 'edit', 'move', 'examine', 'limit', 'delete'] as $key) {

                    if ($key == 'sticky') {
                        if($is_user_special || $is_circle_master){
                            if($scene != 90001){
                                $lists[] = [
                                    'name' => $sticky_name,
                                    'action' => 'sticky',
                                    'posts_id' => $v->id,
                                    'scene' => $scene
                                ];
                                if($scene == 6 || $scene == 9){
                                    if($v->circle_id){
                                        $sticky_posts = _empty_default_(get_circle_meta($v->circle_id, 'sticky_notice_list', 'j'), []);
                                        $lists[] = [
                                            'name' => in_array($v->id, $sticky_posts) ? '取消公告' : '置顶公告',
                                            'action' => 'sticky',
                                            'posts_id' => $v->id,
                                            'scene' => 60001
                                        ];
                                    }
                                }
                            }
                        }else if($uid == $v->user_id){
                            if($v->posts_state === 0 && $v->is_examine == 1){
                                if($scene == 5 || $scene == 8){
                                    $lists[] = [
                                        'name' => $sticky_name,
                                        'action' => 'sticky',
                                        'posts_id' => $v->id,
                                        'scene' => $scene
                                    ];
                                }
                            }
                        }
                    } else if ($key == 'edit') {
                        if($is_user_special || ($uid == $v->user_id && $v->posts_state === 0)){
                            if($v->refer_id > 0 || $v->voter_id > 0 || $v->vote_id > 0){

                            }else{
                                $lists[] = [
                                    'name' => '重新编辑',
                                    'action' => 'slider',
                                    'target_type' => 6,
                                    'target_id' => '/pages/creat/index/creat?edit=' . $v->id
                                ];
                            }
                        }
                    } else if ($key == 'move') {
                        if($is_user_special){
                            $lists[] = [
                                'name' => '转移圈子',
                                'action' => 'move',
                                'posts_id' => $v->id,
                            ];
                        }
                    } else if ($key == 'examine') {
                        if($v->posts_state === 0 && $uid == $v->user_id && $v->is_examine == 1){
                            $lists[] = [
                                'name' => '转为草稿',
                                'action' => 'examine',
                                'posts_id' => $v->id,

                            ];
                        }else if($is_user_special || $is_circle_master){
                            if($v->is_examine == 1){
                                $lists[] = [
                                    'name' => '快速驳回',
                                    'action' => 'examine',
                                    'posts_id' => $v->id,
                                ];
                            }else{
                                $lists[] = [
                                    'name' => '审核通过',
                                    'action' => 'examine',
                                    'posts_id' => $v->id,
                                ];
                            }
                        }
                    } else if ($key == 'delete') {
                        if($is_user_special || $is_circle_master || $uid == $v->user_id){
                            if($scene != 90001){
                                $lists[] = [
                                    'name' => '删除笔记',
                                    'action' => 'delete',
                                    'posts_id' => $v->id,
                                ];
                            }
                        }
                    }else if ($key == 'limit') {
                        global $__MINI_GLOBAL_PAYCODE_5__;
                        if($__MINI_GLOBAL_PAYCODE_5__ && $is_user_special){
                            if($scene != 90001){
                                $lists[] = [
                                    'name' => '首页限流',
                                    'action' => 'limit',
                                    'posts_id' => $v->id,
                                ];
                            }
                        }
                    }
                }

                if($lists){
                    $longtaps[] = [
                        'text' => '管理',
                        'emoji' => '💡',
                        'list' => $lists
                    ];
                }
            }
        }
        $v->longtaps = $longtaps;
    }

    public static function circleProcess(&$v, $uid, $scene){
        if($v->circle_id > 0){
            if($scene == 9){
                $v->circle = WxCircleRepositores::CircleInfo($v->circle_id);
            }else{
                $v->circle = WxCircle::where('id', $v->circle_id)->first(FieldUtils::circleInfoColums());//圈子
            }
        }else{
            $v->circle = null;
        }
        if($v->circle){
            if($v->circle['is_follow_pay'] || $v->circle['is_follow_vip'] || $v->circle['is_follow_authentication'] || $v->circle['is_follow_admin']){
                $v->circle['can_i_visit'] = CircleUtils::can_i_visit($v->circle, $uid);
            }
        }
    }

    public static function WaterfallProcess($k, &$v, $scene = 0, $actree = null){
        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        Redis::sadd('robot:timed:post:active', $v->id);

        global $__MINI_GLOBAL_DEVICE__;
        self::circleProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene);

        if($v->has_fields === 1) {
            $v->fields = WxPostsField::find($v->id);
        }else if($v->has_fields === null){
            $v->fields = WxPostsField::find($v->id);
            UpdatePostFieldsJob::dispatch($v->id);
        }


        if($v->video_id === Null){
            $v->video = WxPostsVideo::where('posts_id', $v->id)->first();//视频
            UpdatePostVideoIdJob::dispatch($v->id);
        }else if($v->video_id > 0){
            $v->video = WxPostsVideo::where('id', $v->video_id)->first();//视频
        }else if($v === 0){
            $v->video = null;
        }

        if($v->is_wechat_sph){
            $v->wechat_sph = get_post_meta($v->id, 'wechat_sph', 'j');
        }else{
            $v->wechat_sph = null;
        }

        //  注意这里不能直接截取，需要长度判断是否是有媒体文件
        $v->posts_content_origin = $v->posts_content;
        $v->posts_content_raw = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '',$v->posts_content_origin );
        $old_post_type = $v->post_type;
        $v->post_type = self::post_type($v);
        if($v->post_type && $old_post_type != $v->post_type){
            Redis::sadd('post:type:to:update:set', json_encode(['id'=>$v->id, 'type'=>$v->post_type]));
        }


        if($__MINI_GLOBAL_DEVICE__ == 'pc'){
            self::interact_process($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene);
        }

        // 图片处理开始
        $img_count = 0;
        $img_url = '';
        $relat_cover = '';

        if($v->post_type == 'single'){
            $images_arr = [];
            $v->posts_content = preg_replace_callback("/<img.*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", function ($r) use (&$images_arr){
                $images_arr[] = $r[1];
                return '';
            }, $v->posts_content);
            if($images_arr){
                $img_count += count($images_arr);
                $img_url = $images_arr[0];
            }
        }else{
            $v->images = WxPostsImg::where('posts_id', $v->id)->get(['id','img_url', 'posts_id','width', 'height']);
            if($v->images){
                $first_img = ($v->images)->first();
                if($first_img){
                    self::postImgScale($first_img, true);
                    $img_url =  $first_img->img_url;
                    if($first_img->width <= 0){
                        UpdatePostImgWHJob::dispatch($first_img->id);
                    }
                }else{
                    $img_url = '';
                }
                $img_count += $v->images->count();
            }
//            if($__MINI_GLOBAL_DEVICE__ == 'pc' && $v->images){
//                $v->images->map( function ($postImg){
//                    $postImg->img_url = Utils::imgWithStyle($postImg->img_url, 1);
//                    return $postImg;
//                });
//            }
        }

        if($v->video && $v->video->video_thumb_url){
            $img_url = $v->video->video_thumb_url;
        }
        if($v->video){
            $img_count += 1;
        }
        if($v->wechat_sph && _array_key($v->wechat_sph, 'img', '')){
            $img_count += 1;
        }

        if($v->wechat_sph && _array_key($v->wechat_sph, 'img', '')){
            $img_count += 1;
        }

        if($v->swiper_max_height){
            $v->swiperImgHeight = $v->swiper_max_height;
        }else{
            $v->swiperImgHeight = 400;
        }

        if($v->img_count != $img_count ){
            UpdatePostImgCountJob::dispatch($v->id, $img_count, 0)->delay(now()->addSeconds(10));
            $v->img_count = $img_count;
        }
        if($img_count == 0 && _empty_($img_url)){
            $v->random_bg = self::get_post_random_bg($v->id);
        }else{
            $v->random_bg = null;
        }

        if ($img_url) {
            $v->img = Utils::imgWithStyle($img_url, 1);
        }else if($v->wechat_sph && _array_key($v->wechat_sph, 'img', '')){
            $v->img = $v->wechat_sph['img'];
        }else{
            self::relatProcess($v, $relat_cover);
            if($relat_cover){
                $v->img = $relat_cover;
                $v->random_bg = null;
            }else{
                $v->img = Utils::imgWithStyle(Settings::get('img_default', ''), 1);
            }
        }

        //图片 处理结束
        self::payContentProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene);
        $v->is_like = WxLike::where('user_id', $__MINI_GLOBAL_CURRENT_USER_ID__)->where('posts_id', $v->id)->exists();
        $v->like_count = PostsRepositores::likeCont($v->id);
        $v->user = UserUtils::get_cached_user($v->user_id);

        $v->posts_content_raw = trim_all_space(strip_tags( html_entity_decode(_mini_phone(_mini_aite_replace(_mini_emoji($v->posts_content_raw, true), true), true)), ['<br>']), true, true);

        if($scene == 75){
            $v->posts_content_raw = self::get_the_title($v->posts_content_raw, $v->id, 100);
        }else{
            $v->posts_content_raw = self::get_the_title($v->posts_content_raw, $v->id, 15);
        }
//        if(mb_strlen($v->posts_content_raw) > 19){
//            $v->posts_content_raw = mb_substr($v->posts_content_raw, 0, 19).'...';
//        }
        if($actree){
            $ac_res = $actree->search($v->posts_content_raw);
            $pre_tags = '<span style="color: '.Settings::get('app_search_highlight_color').';">';
            $end_tag =   '</span>';
            $_tmp_posts_content_raw = $v->posts_content_raw;
            if($v->post_type == 'single'){

                if(mb_strlen($_tmp_posts_content_raw) > 55){
                    $_tmp_posts_content_raw = mb_substr($_tmp_posts_content_raw, 0, 55) . '...';
                }
            }else{
                if(mb_strlen($_tmp_posts_content_raw) > 100){
                    $_tmp_posts_content_raw = mb_substr($_tmp_posts_content_raw, 0, 100) . '...';
                }
            }
            foreach ($ac_res as $pos) {
                $searched_part = mb_substr($v->posts_content_raw,$pos[0],$pos[1] - $pos[0],'UTF-8');
                if(str_contains(self::$app_emoji_alt_str, $searched_part)){
                    $v->posts_content = str_replace($searched_part, $pre_tags.$searched_part.$end_tag, $v->posts_content);
                    $_tmp_posts_content_raw = str_replace($searched_part, $pre_tags.$searched_part.$end_tag, $_tmp_posts_content_raw);
                }
            }
            $v->posts_content_raw = $_tmp_posts_content_raw;
        }else{
            if($v->post_type == 'single'){
                if(mb_strlen($v->posts_content_raw) > 55){
                    $v->posts_content_raw = mb_substr($v->posts_content_raw, 0, 55) . '...';
                }
            }else{
                if(mb_strlen($v->posts_content_raw) > 100){
                    $v->posts_content_raw = mb_substr($v->posts_content_raw, 0, 100) . '...';
                }
            }

        }

        if($scene){
            if($scene == 1){
            }else if($scene == 6){
                if( get_circle_meta($v->circle_id, 'sticky', 'n') == $v->id ){
                    $v->is_sticky = true;
                }else{
                    $v->is_sticky = false;
                }
            }else if($scene == 5 || $scene == 8){
                if( get_user_meta($v->user_id, 'sticky', 'n') == $v->id ){
                    $v->is_sticky = true;
                }else{
                    $v->is_sticky = false;
                }
            }else{
                $v->is_sticky = false;
            }
        }else{
            $v->is_sticky = false;
        }

        if($v->video && _empty_($v->video->video_thumb_url)){
            $v->video->video_thumb_url = Settings::get('img_video_default');
        }
        $v->posts_content_raw = _mini_emoji($v->posts_content_raw);

        if(($k + 1) % 8 == 0){
            self::get_ad($v, $scene, true);
        }else{
            $v->ad = null;
        }

        if($v->distance && $v->distance > 0){
//            $v->distance = (int)(1000 * $v->distance);
            if($v->distance < 10){
                $v->distance = '<10m';
            }else if($v->distance >= 1000 && $v->distance <= 200000){
                $v->distance = '<'. round($v->distance / 1000, 2).'km';
            }else if($v->distance > 200000){
                $v->distance = round($v->distance / 1000, 2).'km';
            }else{
                $v->distance = '<'.(int)$v->distance.'m';
            }
        }else{
            $v->distance = '';
        }

//        self::voteProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__);

//        self::referProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene, 1);

        self::longtapProcess($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene, 1);
        $v->view_count = self::get_view_count($v->id);
        self::mediaStyle($v, $scene);

        self::presets($v, $__MINI_GLOBAL_CURRENT_USER_ID__, $scene, true);

        return $v;
    }


    public static function get_view_count($post_id){
        $view_count = (int)(Cache::remember('post:view:count:'.$post_id, 3600, function () use ($post_id){
            return WxUserVisit::where('type', 1)->where('object_id', $post_id)->count();
        }));
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
        if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
            return $view_count;
        }

        return $view_count;
    }

    public static function interact_process(&$v, $uid, $scene)
    {
        global $__MINI_GLOBAL_CURRENT_USER_ID__;
        $v->address = self::get_post_address($v->address_id);
        $v->like_count = PostsRepositores::likeCont($v->id); // 笔记喜欢数量
        $v->is_my_posts = $__MINI_GLOBAL_CURRENT_USER_ID__ == $v->user_id; // 是否是我的笔记
        $v->is_follow_user = Model::isFollowUser($uid, $v->user_id);// 是否关注该用户
        $v->is_like = Model::isLike($uid, $v->id); // 是否喜欢
        $v->is_collect = Model::isCollec($uid, $v->id); // 是否收藏

        if( !_empty_($v->tags_id) ){
            $v->tags = WxTag::whereIn('id', explode(',', $v->tags_id))->get(['tags_name', 'id']);
        }else if($v->tags_id === ''){
            $v->tags = null;
        }else if($v->tags_id === '0'){
            $v->tags = PostsRepositores::getPostTags($v->id);
            UpdatePostTagIdJob::dispatch($v->id);
        }

        if( !_empty_($v->goods_id) ){
            $v->goods = WxShopGoods::whereIn('id', explode(',', $v->goods_id))->get(['id', 'pic', 'name', 'credit_type', 'intro', 'price', 'vip_price', 'tk_platform_id', 'buys']);
        }else if($v->goods_id === ''){
            $v->goods = null;
        }else if($v->goods_id === '0'){
            $v->goods = PostsRepositores::getPostGoods($v->id);
            UpdatePostGoodsIdJob::dispatch($v->id);
        }

        if( !_empty_($v->files_id) ){
            $v->files = WxPostsFile::whereIn('id', explode(',', $v->files_id))->get();
        }else if($v->files_id === ''){
            $v->files = null;
        }else if($v->files_id === '0'){
            $v->files = PostsRepositores::getPostFiles($v->id);
            UpdatePostFilesIdJob::dispatch($v->id);
        }


        if( !_empty_($v->sounds_id) ){
            $v->sounds = WxPostsSound::whereIn('id', explode(',', $v->sounds_id))->get();
        }else if($v->sounds_id === ''){
            $v->sounds = null;
        }else if($v->sounds_id === '0'){
            $v->sounds = PostsRepositores::getPostSounds($v->id);
            UpdatePostSoundsIdJob::dispatch($v->id);
        }

//        $v->comment = (new Model())
//            ->getComment($v->id, ['user_name', 'comment_content', 'user_id', 'posts_user_id', 'comment_img_url']);
        $v->comment_count = WxCommentRepositores::commentCount($v->id);//评论数量
        if($v->comment_count > 0){
            $v->popular_comment = json_decode(Cache::get('post:popular:comment:'.$v->id, '[]'), true);
            if(_empty_($v->popular_comment)){
                Redis::sadd('post:popular:comment:set', $v->id);
            }
        }else{
            $v->popular_comment = null;
        }


        $v->exceptional_count = PostsRepositores::exceptionalCont($v->id); // 充电总数
        $v->exceptional = PostsRepositores::exceptionalList($v->id);//获取笔记充电列表
        $v->collected_count = StatisticUtils::post_becollected_count($v->id);
        $v->showComment = false;

    }



    public static function get_post_random_bg($post_id){
        return Cache::remember('post:randombg:'.$post_id, 36000, function () use ($post_id){
            $random_bg = get_post_meta($post_id, 'random_bg', 'n');
            if(_empty_($random_bg)){
                $random_bg = mini_rand(1, 12);
                $random_bg_img = Settings::get('sticky_random_bg_'.$random_bg, '', true);
                if(_empty_($random_bg_img)){
                    $random_bg = mini_rand(1, 4);
                    $random_bg_img = Settings::get('sticky_random_bg_'.$random_bg, '', true);
                }
                update_post_meta($post_id, 'random_bg', $random_bg, 'n');
            }else{
                $random_bg_img = Settings::get('sticky_random_bg_'.$random_bg, '', true);
            }
            return $random_bg_img;
        });
    }

    public static function get_post_address($address_id){
        if(_empty_($address_id)){
            return null;
        }
        $address_obj = WxPostsAddress::where('id', $address_id)->first();
        if($address_obj){
            return $address_obj;
        }
        return null;
    }


    public static function get_post_str_desc($post_id){
        if(_empty_($post_id)){
            return null;
        }
        $str = PostUtils::get_the_title('', $post_id);
        $post_tags = PostsRepositores::getPostTags($post_id);
        if($post_tags){
            foreach ($post_tags as $tag){
                $str .= ' '.$tag['tags_name'];
            }
        }
    }

//    public static function

    public static function get_flow(){
        global $__MINI_GLOBAL_IP__,$__MINI_GLOBAL_PAYCODE_0__;

        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return null;
        }

        // 1: 圈子 2：话题 3：用户 4：笔记
        $flow_type = Cache::get('flow:'.$__MINI_GLOBAL_IP__, '4');
        $type = '1';
        switch ($flow_type){
            case '1':
                $type = _array_rand_element(['2', '3']);
                break;
            case '2':
                $type = _array_rand_element(['1', '3']);
                break;
            case '3':
                $type = _array_rand_element(['1', '2']);
                break;
            case '4':
                $type = _array_rand_element(['1', '2', '3']);
                break;
        }
        Cache::forget('flow:'.$__MINI_GLOBAL_IP__);
        Cache::put('flow:'.$__MINI_GLOBAL_IP__, $type, 3600);

        if($type == '1'){
            $flow = self::get_circles_flow();
            if($flow){
                return ['type'=>'1', 'flow' => $flow];
            }
        }else if($type == '2'){
            $flow = self::get_topics_flow();
            if($flow){
                return ['type'=>'2', 'flow' => $flow];
            }
        }else if($type == '3'){
            $flow = self::get_users_flow();
            if($flow){
                return ['type'=>'3', 'flow' => $flow];
            }
        }
    }


    private static function get_ad(&$v, $scene, $is_water){
        global $__MINI_GLOBAL_DEVICE__, $__MINI_GLOBAL_PAYCODE_14__;
        if(!$__MINI_GLOBAL_PAYCODE_14__){
            return;
        }

        if(mini_current_user(1) && Settings::get('app_vip_ad_shut', 0) == 1){
            return;
        }

        // 广告
        if(self::$ad_config === null){
            self::$ad_config = json_decode(Cache::get(_multi_key('ad_config'), '[]'), true);
            if(_empty_(self::$ad_config)){
                CheckBatchCahceDataLossJob::dispatch();
            }
        }

        if(self::$ad_config){
            if($scene == 9){
                // 详情广告
                if($__MINI_GLOBAL_DEVICE__ == 'mp'){
                    if($v->post_type == 'words'){
                        if(self::$ad_config['mp']['position1']['words']){
                            $v->ad = _array_rand_element(self::$ad_config['mp']['position1']['words']);
                        }
                    }else if($v->post_type == 'single'){
                        if(self::$ad_config['mp']['position1']['single']){
                            $v->ad = _array_rand_element(self::$ad_config['mp']['position1']['single']);
                        }
                    }else if($v->post_type == 'video'){
                        if(self::$ad_config['mp']['position1']['video']){
                            $v->ad = _array_rand_element(self::$ad_config['mp']['position1']['video']);
                        }
                    }
                }else{
                    if($v->post_type == 'words'){
                        if(self::$ad_config['uni']['position1']['words']){
                            $v->ad = _array_rand_element(self::$ad_config['uni']['position1']['words']);
                        }
                    }else if($v->post_type == 'single'){
                        if(self::$ad_config['uni']['position1']['single']){
                            $v->ad = _array_rand_element(self::$ad_config['uni']['position1']['single']);
                        }
                    }else if($v->post_type == 'video'){
                        if(self::$ad_config['uni']['position1']['video']){
                            $v->ad = _array_rand_element(self::$ad_config['uni']['position1']['video']);
                        }
                    }
                }
            }else{
                if($is_water){
                    if($__MINI_GLOBAL_DEVICE__ == 'mp'){
                        if(self::$ad_config['mp']['position4']['flow']){
                            $v->ad = _array_rand_element(self::$ad_config['mp']['position4']['flow']);
                        }
                    }else{
                        if(self::$ad_config['uni']['position4']['flow']){
                            $v->ad = _array_rand_element(self::$ad_config['uni']['position4']['flow']);
                        }
                    }
                }else{
                    if($__MINI_GLOBAL_DEVICE__ == 'mp'){
                        if(self::$ad_config['mp']['position4']['flow']){
                            $v->ad = _array_rand_element(self::$ad_config['mp']['position2']['flow']);
                        }
                    }else{
                        if(self::$ad_config['uni']['position4']['flow']){
                            $v->ad = _array_rand_element(self::$ad_config['uni']['position2']['flow']);
                        }
                    }
                }
            }
        }
        if(_empty_($v->ad)){
            $v->ad = null;
        }
    }

    public static function get_circles_flow($cache_key = null){
        global $__MINI_GLOBAL_TENANT_ID__;
        if($cache_key == null) {
            $cache_key = 'flow:circles:'.$__MINI_GLOBAL_TENANT_ID__.':' . mini_rand(1, 4);
            if(Cache::has($cache_key)) {
                return Cache::remember($cache_key, 1500, function () {
                    $circles_top = RealtimeUtils::get_circle_top();
                    if ($circles_top) {
                        $circles_top = $circles_top['circles'];
                        return _array_rand_element($circles_top, 4);
                    }
                    return [];
                });
            }
        }else{
            Cache::forget($cache_key);
            return Cache::remember($cache_key, 1500, function () {
                $circles_top = RealtimeUtils::get_circle_top();
                if ($circles_top) {
                    $circles_top = $circles_top['circles'];
                    return _array_rand_element($circles_top, 4);
                }
                return [];
            });
        }

        return [];
    }

    public static function get_topics_flow($cache_key = null){
        if($cache_key == null) {
            $cache_key = 'flow:topics:' . mini_rand(1, 8);
            if(Cache::has($cache_key)) {
                return Cache::remember($cache_key, 1500, function () {
                    $topics_top = RealtimeUtils::get_topic_top();
                    if ($topics_top) {
                        $topics_top = $topics_top['topics'];
                        return _array_rand_element($topics_top, 4);
                    }
                    return [];
                });
            }
        }else{
            Cache::forget($cache_key);
            return Cache::remember($cache_key, 1500, function () {
                $topics_top = RealtimeUtils::get_topic_top();
                if ($topics_top) {
                    $topics_top = $topics_top['topics'];
                    return _array_rand_element($topics_top, 4);
                }
                return [];
            });
        }
        return [];
    }

    public static function get_users_flow($cache_key = null){
        global $__MINI_GLOBAL_TENANT_ID__;
        if($cache_key == null){
            $cache_key = 'flow:users:'.$__MINI_GLOBAL_TENANT_ID__.':' . mini_rand(1,7);
            if(Cache::has($cache_key)){
                return Cache::remember($cache_key, 1500, function (){
                    $users_top = RealtimeUtils::get_user_top();
                    if($users_top){
                        $users_top = $users_top['users'];
                        return _array_rand_element($users_top, 6);
                    }
                    return [];
                });
            }
        }else{
            Cache::forget($cache_key);
            return Cache::remember($cache_key, 1500, function (){
                $users_top = RealtimeUtils::get_user_top();
                if($users_top){
                    $users_top = $users_top['users'];
                    return _array_rand_element($users_top, 6);
                }
                return [];
            });
        }

        return [];
    }



    /** 利用地址引用，增加 posts_content_raw 字段
     * @param $post
     * @return string
     */
    public static function post_type(&$post){
        return Cache::remember('posts:post_type:'.$post->id, 36000, function () use (&$post){
            if(_empty_($post)){
                return '';
            }

            if($post->video){
                return 'video';
            }

            // 存在媒体文件或者长度大于150判断为长文章
            if( ( strlen($post->posts_content_raw) != strlen($post->posts_content) ) || mb_strlen($post->posts_content_raw) > 2500 ){
                return 'single';
            }
            if(preg_match('/<(img|video|table|audio)[^>]+>/is', $post->posts_content)){
                return 'single';
            }

            return 'words';
        });
    }


    private static function payContentProcess(&$v, $uid, $scene){
        $pay_obj = [
            'is_payd' => false,
            'price' => 0,
            'pay_type' => -1,
            'credit' => '',
            'hidden' => '',
            'words_percent' => 100,
            'has_hidden' => 0,
            'has_file' => 0,
            'has_img' => 0,
            'has_video' => 0
        ];

        // 处理付费情景 pay_type: 0金币 1 余额
        if($v->pay_content_id > 0){
            $pay_content_obj = WxPostsPayContent::find($v->pay_content_id);
            if($pay_content_obj){
                $pay_obj['price'] = $pay_content_obj->price;
                // 付费icon
                if($pay_content_obj->credit_type == 0){
                    $pay_obj['pay_type'] = 0;
                    $pay_obj['credit'] = Settings::get('app_coin_name', '硬币');
                }else if($pay_content_obj->credit_type == 1){
                    $pay_obj['pay_type'] = 1;
                    $pay_obj['credit'] = '余额';
                }


                $is_payed = false;
                if($uid > 0){
                    // 登录情况下
                    $is_payed = WxUserPay::where([
                        ['user_id', '=', $uid],
                        ['post_id', '=', $v->id],
                        ['pay_content_id', '=', $v->pay_content_id]
                    ])->exists();
                    if($uid == $v->user_id){
                        if($scene == 8){
                            $is_payed = false;
                        }else{
                            $is_payed = true;
                        }
                    }
                }
                if($is_payed){
                    $pay_obj['is_payd'] = true;
                    if($pay_content_obj->hidden){
                        $pay_obj['hidden'] = $pay_content_obj->hidden;
                        $v->posts_content .= '<hidden text="'.str_replace('"', "'", $pay_content_obj->hidden).'"></hidden>';
                        $v->is_only_text = 0;
                    }
                }else{
                    // 未付费情况下
                    // 处理文件付费
                    if($pay_content_obj->is_file && $v->files){
                        $pay_obj['has_file'] = count($v->files);
                        $v->files->map(function ($v){
                            $v->url = '';
                            $v->is_pay = 1;
                        });
                    }

                    if($pay_content_obj->is_img && $v->images){
                        $pay_obj['has_img'] = count($v->images);
                        $v->images->map(function ($v){
                            $v->is_pay = 1;
                        });
                    }

                    if($pay_content_obj->is_video && $v->video_id > 0){
                        $pay_obj['has_video'] = 1;
                        $v->video['is_pay'] = 1;
                    }

                    // 处理篇幅付费
                    if($pay_content_obj->words_percent != 100){
                        $pay_obj['words_percent'] = $pay_content_obj->words_percent;
                        $v->posts_content = self::truncateHTML($v->posts_content, $pay_content_obj->words_percent);
                    }

                    // 处理隐藏内容
                    if($pay_content_obj->hidden){
                        $pay_obj['has_hidden'] = mb_strlen($pay_content_obj->hidden);
                    }

                }
            }
        }
        $v->pay_obj = $pay_obj;
    }


    private static function voteProcess(&$post, $uid){

        if($post->vote_id === Null){
            UpdatePostVoteIdJob::dispatch($post->id);
        }else if($post->vote_id > 0){

        }else if($post->vote_id === 0){
            $post->vote = [];
            return;
        }

        // 这里处理投票
        $the_vote = WxPostsVote::where('post_id', $post->id)->first(['id', 'option1', 'num1', 'option2', 'num2', 'option3', 'num3', 'option4', 'num4', 'option5', 'num5',
            'option6', 'num6', 'option7', 'num7', 'option8', 'num8', 'option9', 'num9', 'option10', 'num10', 'option11', 'num11', 'option12', 'num12', 'option13', 'num13',
            'option14', 'num14','option15', 'num15','option16', 'num16', 'option17', 'num17', 'option18', 'num18', 'option19', 'num19', 'option20', 'num20']);//投票
        if($the_vote){

            $vote_option = WxUserVote::where([['user_id', '=', $uid], ['vote_id', '=', $the_vote->id]])->value('vote_option');
            if(_empty_($vote_option)){
                $vote_option = 0;
            }

            $total_num = ( $the_vote->num1 + $the_vote->num2 + $the_vote->num3 + $the_vote->num4 + $the_vote->num5 + $the_vote->num6 + $the_vote->num7 + $the_vote->num8 + $the_vote->num9 + $the_vote->num10
                + $the_vote->num11 + $the_vote->num12 + $the_vote->num13 + $the_vote->num14 + $the_vote->num15 + $the_vote->num16 + $the_vote->num17 + $the_vote->num18 + $the_vote->num19 + $the_vote->num20 );
            $voteItem = [
                'id' => $the_vote->id,
                'title' => $post->posts_content_raw,
                'nickname' => $post->user ? $post->user['user_name'] : '未知',
                'user_id' => $post->user ? $post->user['id'] : 0,
                'nums' => $total_num,
                'voted' => $vote_option > 0,
                'voted_title' => '',
                'vtList' => []
            ];

            foreach ([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] as $num){
                if($the_vote['option'.$num]){
                    $voteItem['vtList'][] = [
                        'p' => $num,
                        'title' => $the_vote['option'.$num],
                        'num'=> $vote_option > 0 ? $the_vote['num'.$num] : '',
                        'percent'=> $vote_option > 0 ? self::getPercentStr($the_vote['num'.$num], $total_num) : '',
                        'selected'=> ($vote_option == $num)
                    ];
                    if($vote_option == $num){
                        $voteItem['voted_title'] = '已选择"'.$the_vote['option'.$num].'"';
                    }
                }
            }

            if(_empty_($voteItem['voted_title'])){
                $voteItem['voted_title'] = '您还未投票';
            }

            $post->vote = $voteItem;
        }else{
            $post->vote = [];
        }
    }

    public static function getVoteData($vote_id, $uid){
        $post_id = WxPostsVote::getPostId($vote_id);
        if(_empty_($post_id)){
            return null;
        }
        $post = WxPost::find($post_id);
        if(_empty_($post)){
            return null;
        }

        // 这里处理投票
        $the_vote = WxPostsVote::where('post_id', $post_id)->first(['id', 'option1', 'num1', 'option2', 'num2', 'option3', 'num3', 'option4', 'num4', 'option5', 'num5',
            'option6', 'num6', 'option7', 'num7', 'option8', 'num8', 'option9', 'num9', 'option10', 'num10', 'option11', 'num11', 'option12', 'num12', 'option13', 'num13',
            'option14', 'num14','option15', 'num15','option16', 'num16', 'option17', 'num17', 'option18', 'num18', 'option19', 'num19', 'option20', 'num20']);//投票
        $vote_option = WxUserVote::where([['user_id', '=', $uid], ['vote_id', '=', $the_vote->id]])->value('vote_option');
        $total_num = ( $the_vote->num1 + $the_vote->num2 + $the_vote->num3 + $the_vote->num4 + $the_vote->num5 + $the_vote->num6 + $the_vote->num7 + $the_vote->num8 + $the_vote->num9 + $the_vote->num10
            + $the_vote->num11 + $the_vote->num12 + $the_vote->num13 + $the_vote->num14 + $the_vote->num15 + $the_vote->num16 + $the_vote->num17 + $the_vote->num18 + $the_vote->num19 + $the_vote->num20 );
        $post->posts_content_raw = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '',$post->posts_content);
        $voteItem = [
            'id' => $the_vote->id,
            'post_id' => $the_vote->post_id,
            'title' => $post->posts_content_raw,
            'nickname' => $post->user['user_name'],
            'user_id' => $post->user['id'],
            'voted' => $vote_option > 0,
            'voted_title' => '',
            'nums' => $total_num,
            'vtList' => []
        ];

        foreach ([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] as $num){
            if($the_vote['option'.$num]){
                $voteItem['vtList'][] = [
                    'p' => $num,
                    'title' => $the_vote['option'.$num],
                    'num'=> $vote_option > 0 ? $the_vote['num'.$num] : '',
                    'percent'=> $vote_option > 0 ? self::getPercentStr($the_vote['num'.$num], $total_num) : '',
                    'selected'=> ($vote_option == $num)
                ];
                if($vote_option == $num){
                    $voteItem['voted_title'] = '已选择"'.$the_vote['option'.$num].'"';
                }
            }
        }

        if(_empty_($voteItem['voted_title'])){
            $voteItem['voted_title'] = '您还未投票';
        }

        return $voteItem;
    }

    public static function truncateHTML($html_string, $percent, $append = '...', $is_html = true)
    {
        $text_len = mb_strlen(strip_tags($html_string));
        $length = $text_len * ($percent / 100);
//        $html_string = trim($html_string);
//        $append = $text_len > $length ? $append : '';
        $i = 0;
        $tags = [];

        if ($is_html) {
            self::preg_match_all_mb('/<[^>]+>([^<]*)/', $html_string, $tag_matches);

            foreach ($tag_matches as $tag_match) {
                if ($tag_match[0][1] - $i >= $length) {
                    break;
                }
                $tag = mb_substr(strtok($tag_match[0][0], " \\\t\\\0\\\x0B>"), 1);
                if ($tag[0] != '/') {
                    if (!in_array($tag, ['img'])) {       //针对有些话题是单话题的情况，不需要成对出现
                        $tags[] = $tag;
                    }
                } elseif (end($tags) == mb_substr($tag, 1)) {
                    array_pop($tags);
                } else {      // </*> 匹配对应的tag话题，然后去掉 tags 中对应的话题
                    while (end($tags) != substr($tag, 1)) {
                        array_pop($tags);
                    }
                    array_pop($tags);
                }
                $i += $tag_match[1][1] - $tag_match[0][1];
            }
        }

        return mb_substr($html_string, 0, $length = min(mb_strlen($html_string), $length + $i)) . $append . (count($tags = array_reverse($tags)) ? '</' . implode('></', $tags) . '>' : '');
    }

    private static function preg_match_all_mb($pattern, $subject, array &$matches = null)
    {
        preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        $strlen0 = 0;
        foreach ($matches as &$match) {
            $matchDt = $match[1][1]-$match[0][1];
            $match[0][1] = $strlen0;
            $match[1][1] = $match[0][1]+$matchDt;

            $strlen0 += mb_strlen($match[0][0]);
        }
    }

    public static function get_post_circle_user_id($post_id){
        if(_empty_($post_id)){
            return null;
        }
        return (int)(Cache::remember('get_post_circle_user_id:'.$post_id, 3600, function () use ($post_id){
            $circle_id = WxPost::where('id', $post_id)->value('circle_id');
            if($circle_id){
                return WxCircle::where('id', $circle_id)->value('user_id');
            }
            return 0;
        }));
    }


    public static function get_the_title($s_content, $post_id, $words = 30){
        // $words只能15,30,100
        return Cache::remember('get_the_title:'.$post_id.':'.$words, 36000, function () use ($s_content, $post_id, $words){

            if(_empty_($s_content)){
                $posts_content = WxPost::where('id', $post_id)->value('posts_content');
                if($posts_content){
                    $s_content = preg_replace("/<(img|video).*?src[^\'\"]+[\'\"]([^\"\']+)[^>]+>/is", '', $posts_content);
                    $s_content =trim_all_space(strip_tags(html_entity_decode($s_content), ['<br>']), true, true);
                }
            }
$s_content = trim(str_replace(["
", '<br>', '<br/>'], "\n", $s_content));
            if(_empty_($s_content)){
                return '';
            }
            $arr = self::strpos_($s_content, ["
",',','，','.','。',':','：',';','；','、','?', '？',' ','!','！', "\n", '<br>'], $words);
            if($arr[0] === -1){
                $arr = self::strpos_($s_content, ['啊','阿','呀','吖','~', '哦', '嗷','啦', '哈', '滴', '吗'], $words);
            }
            if($arr[0] !== 9999){
                if(in_array($arr[1], [',','，','.','。',':','：',';','；','、'])){
                    $title = mb_substr($s_content, 0, $arr[0]);
                }else{
                    $title = mb_substr($s_content, 0, $arr[0] + 1);
                }
                if(mb_strlen($title) < 10 || mb_strlen($title) > 1.5 * $words){
                    if(mb_strlen($s_content) > $words){
                        return trim_all_space(mb_substr($s_content, 0, $words), true).'...';
                    }else{
                        return trim_all_space($s_content, true);
                    }
                }
                return trim_all_space($title, true);
            }else{
                if(mb_strlen($s_content) > $words){
                    return trim_all_space(mb_substr($s_content, 0, $words), true).'...';
                }else{
                    return trim_all_space($s_content, true);
                }
            }
        });

    }

    private static function getPercentStr($num1, $num2){
        if($num1 === 0 || $num2 === 0){
            return '0%';
        }
        $per = (string) (round( $num1 / $num2, 2) * 100 ) ;
        return $per.'%';
    }

    public static function strpos_($content, $finds = [], $words =  30){
        $min_index = 9999;
        $min_value = 9999;
        $find_ = '';
        foreach ($finds as $find){

            $j = 0;
            $arr = array();
            $count = substr_count($content, $find);
            for($i = 0; $i < $count; $i++){
                $j = mb_strpos($content, $find, $j);
                $arr[] = $j;
                $j = $j+1;
            }
            if($arr){
                foreach ($arr as $find_index){
                    if(  abs(abs($find_index) - $words ) < $min_value){
                        $min_index = $find_index;
                        $find_ = $find;
                        $min_value = abs(abs($find_index) - $words );
                    }
                    if(!in_array($find_, [',','，','、',':','：'])){
                        if($min_value <= 15){
                            return [$min_index, $find_, $min_value];
                        }
                    }else{
                        if($min_value <= 6){
                            return [$min_index, $find_, $min_value];
                        }
                    }

                }
            }
        }
        return [$min_index, $find_, $min_value];
    }

    public static function is_post_author($post_id, $user_id){
        if(_empty_($post_id) || _empty_($user_id)){
            return false;
        }
        return WxPost::isMyPosts($user_id, $post_id);
    }

    public static function post_icon_inline_process($str){
        $str = trim($str);
        if(strpos($str, '<p') === 0){
            $flag = true;
            $str = preg_replace_callback('$<p[^>]*?>(.*?)</p>$', function ($matches) use (&$flag){
                if($flag){
                    $flag = false;
                    return $matches[1];
                }else{
                    return $matches[0];
                }
            }, $str);
        }
        return $str;
    }

    public static function post_md5($user_id, $content, $imgs, $video_url, $pay_content){

    }


    public static function get_post_popular_comment($post_id){
        $comment = WxComment::where('posts_id', $post_id)->where('comment_state', 1)->whereNull('comment_id')->inRandomOrder()->first(['id', 'posts_id', 'user_id', 'user_avatar', 'user_name', 'comment_content', 'comment_img_url']);
        if($comment){
            $comment->comment_content_raw = strip_tags( _mini_phone( _mini_emoji(_mini_aite_replace($comment->comment_content, true), true), true));
            return $comment->toArray();
        }
        return null;
    }


    /*
     * 不会检查状态，强制
     */
    public static function post_pass(WxPost &$post, $flag = 1, $overrule_content = ''){
        $is_need_notice = false;
        if($post->is_examine === 0){
            $is_need_notice = true;
        }
        if($flag == 1){
            WxPost::where('id', $post->id)->update([
                'is_examine' => 1
            ]);
            if($is_need_notice){
                $msg = UserUtils::reward_user_coin($post->user_id, 'publish');
                if($msg){
                    UserUtils::assistant_notice($post->user_id, '您发表的笔记(id:<a href="/pages/sticky/sticky?id='.$post->id.'">'.$post->id.'</a>)已经审核通过，并获得发布奖励：'.$msg);
                }else{
                    UserUtils::assistant_notice($post->user_id,  '您发表的笔记(id:<a href="/pages/sticky/sticky?id='.$post->id.'">'.$post->id.'</a>)已经审核通过啦');
                }
            }
        }else if($flag == 2){
            WxPost::where('id', $post->id)->update([
                'is_examine' => 2
            ]);
            UserUtils::assistant_notice($post->user_id, '您发表的笔记(id:<a href="/pages/sticky/sticky?id='.$post->id.'">'.$post->id.'</a>)被驳回了'.(!_empty_($overrule_content) ? '，驳回原因：'.$overrule_content : ''));
        }
        Cache::forget('total:todo:count');
        Cache::forget('total:tenant:todo:count');
    }

}